package com.jy.event.util;

import com.aliyun.opensearch.DocumentClient;
import com.aliyun.opensearch.OpenSearchClient;
import com.aliyun.opensearch.sdk.dependencies.org.json.JSONArray;
import com.aliyun.opensearch.sdk.dependencies.org.json.JSONObject;
import com.aliyun.opensearch.sdk.generated.OpenSearch;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchClientException;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchException;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchResult;
import com.aliyun.opensearch.sdk.generated.document.Command;
import com.aliyun.opensearch.sdk.generated.document.DocumentConstants;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

/**
 * Created by lihu on 2017/12/15.
 */
@Slf4j
public class OpenSearchUtil {


    private static final String accesskey = "LTAI1MFQKaqHdzSw";
    private static final String secret = "szQyLJryhX4yg0uWccBh3TZUpWAEf2";
    private static final String host = "http://opensearch-cn-hangzhou.aliyuncs.com";

    private static OpenSearch openSearch = null;

    private static OpenSearchClient serviceClient = null;

    static {
        openSearch = new OpenSearch(accesskey, secret, host);
        //创建OpenSearchClient对象，并以OpenSearch对象作为构造参数
        serviceClient = new OpenSearchClient(openSearch);
    }


    public static void push(List<Map<String, Object>> list, String appName, String tableName) {
        //新增及更新都设为ADD，不支持update，当已存在相同主键值文档时做更新，否则新增，此处作为新增
        JSONArray docsJsonArr = new JSONArray();
        for (Map<String, Object> map : list) {
            JSONObject json = new JSONObject();
            json.put(DocumentConstants.DOC_KEY_CMD, Command.ADD.toString());
            json.put(DocumentConstants.DOC_KEY_FIELDS, map);
            docsJsonArr.put(json);//新增文档1
        }
        String docsJson = docsJsonArr.toString();
        log.info("{}", docsJson);

        try {
            DocumentClient documentClient = new DocumentClient(serviceClient);
            //执行推送操作
            OpenSearchResult osr = documentClient.push(docsJson, appName, tableName);
            //判断数据是否推送成功，主要通过判断2处，第一处判断用户方推送是否成功，第二处是应用控制台中有无报错日志
            //用户方推送成功后，也有可能在应用端执行失败，此错误会直接在应用控制台错误日志中生成，比如字段内容转换失败
            if (osr.getResult().equalsIgnoreCase("true")) {
                log.info("用户方推送无报错！\n以下为getTraceInfo推送请求Id:" + osr.getTraceInfo().getRequestId());
            } else {
                log.error("用户方推送报错！" + osr.getTraceInfo());
            }
        } catch (OpenSearchException e) {
            e.printStackTrace();
        } catch (OpenSearchClientException e) {
            e.printStackTrace();
        }

    }


}